import type { Ref } from 'vue';

import type { RowType } from '#/views/system/dict/dictItem/dictItem.data';

import { h, isRef, ref, watch } from 'vue';

import { Badge, message, Tag } from 'ant-design-vue';

import { queryDictCacheApi } from '#/api/system/dict';

export namespace DictUtilsApi {
  export interface DictCacheParams {
    dictCode: string;
  }
  export interface Dictionary {
    [key: string]: Record<string, RowType>;
  }
}

// 实现查询字典options
export const queryDictOptionsApi = async (
  params: DictUtilsApi.DictCacheParams,
) => {
  try {
    return await queryDictCacheApi(params);
  } catch (error) {
    message.error(`字典加载失败:${error}`);
  }
};

// 用于加载数据字典&翻译表格中的字典信息
export function useDictionaries(dictCodes: Ref<string[]> | string[]) {
  // 统一转换为 Ref<string[]>
  const dictCodesRef = isRef(dictCodes) ? dictCodes : ref([...dictCodes]);

  const dictionaries = ref<DictUtilsApi.Dictionary>({});
  const fetchDictionaries = async () => {
    try {
      const codes = dictCodesRef.value;
      if (codes.length === 0) return;
      const response = await queryDictCacheApi({
        dictCode: codes.join(','),
      });
      if (response && Array.isArray(response)) {
        // 清空之前的字典数据
        dictionaries.value = {};
        response.forEach((item) => {
          if (item.status === 0) {
            // 确保每个字典代码都有对应的对象
            if (!dictionaries.value[item.code]) {
              dictionaries.value[item.code] = {};
            }
            dictionaries.value[item.code][item.itemVal] = item;
          }
        });
      }
    } catch (error) {
      message.error(`字典加载失败:${error}`);
    }
  };

  // onMounted(fetchDictionaries);
  watch(
    dictCodesRef,
    (newCodes) => {
      if (newCodes.length > 0) {
        fetchDictionaries();
      }
    },
    { immediate: true },
  );

  const translateValue = (params: any, dictCode: string) => {
    const { row, column } = params;
    const cellValue = row[column.field];
    if (
      !dictionaries.value[dictCode] ||
      !dictionaries.value[dictCode][cellValue]
    ) {
      return h('span', {}, cellValue);
    }
    const dictItem = dictionaries.value[dictCode][cellValue];
    switch (dictItem.showStyle) {
      case 1: {
        return h(Badge, {
          status: dictItem.showStyleColor,
          text: dictItem.itemText,
        });
      }
      case 2: {
        return h(Tag, { color: dictItem.showStyleColor || 'success' }, () => [
          dictItem.itemText,
        ]);
      }
      default: {
        return h('span', {}, dictItem.itemText);
      }
    }
  };

  const translateText = (val: string, dictCode: string) => {
    if (!dictionaries.value[dictCode] || !dictionaries.value[dictCode][val]) {
      return h('span', {}, val);
    }
    const dictItem = dictionaries.value[dictCode][val];
    switch (dictItem.showStyle) {
      case 1: {
        return h(Badge, {
          status: dictItem.showStyleColor,
          text: dictItem.itemText,
        });
      }
      case 2: {
        return h(Tag, { color: dictItem.showStyleColor || 'success' }, () => [
          dictItem.itemText,
        ]);
      }
      default: {
        return h('span', {}, dictItem.itemText);
      }
    }
  };

  return { translateValue, translateText, dictionaries };
}
